package org.ainlolcat.ainscience.UI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 11/4/11
 * Time: 10:47 PM
 * To change this template use File | Settings | File Templates.
 */
public class XListPane extends JPanel {
    //Collection<String> list;
    JList jlist;
    Collection<SelectedValueListener> listeners;

    public interface SelectedValueListener{
        public void handleSelected(String value);
    }

    public XListPane(Collection<String> list){
        super(new BorderLayout());
        listeners = new ArrayList<SelectedValueListener>();
        initFromList(list);
    }

    public XListPane(ListModel model){
        super(new BorderLayout());
        listeners = new ArrayList<SelectedValueListener>();
        initFromListModel(model);
    }
    
    private void initFromList(Collection<String> list){
        jlist = new JList();
        Vector data = new Vector<String>(list);
        Collections.sort(data);
        jlist.setListData(data);
        jlist.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String value = (String)jlist.getSelectedValue();
                for (SelectedValueListener svl:listeners){
                    svl.handleSelected(value);
                }
            }
        });
        JScrollPane scroll = new JScrollPane(jlist);
        scroll.setLayout(new ScrollPaneLayout());
        add(scroll, BorderLayout.CENTER);
    }

    private void initFromListModel(ListModel model){
        jlist = new JList(model);
        jlist.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String value = (String)jlist.getSelectedValue();
                for (SelectedValueListener svl:listeners){
                    svl.handleSelected(value);
                }
            }
        });
        JScrollPane scroll = new JScrollPane(jlist);
        add(scroll, BorderLayout.CENTER);
    }
    
    public void setListData(Collection<String> list){
        Vector data = new Vector<String>(list);
        Collections.sort(data);
        jlist.setListData(data);
    }

    public void addSelectedValueListener(SelectedValueListener svl){
        listeners.add(svl);
    }
}
